import React from "react";
import "./style.css";
import bg from "../../images/login-bg.webp";
import { Form, Input, Button, message as antdMessage } from "antd";
import { LoginRawState } from "../../types";
import axios from "axios";
import { useNavigate } from "react-router-dom";

const Login: React.FC = () => {
  const navigate = useNavigate()
  const finish = async (value: LoginRawState) => {
    // 请求登录接口
    const resp = await axios.post('/api/login', value)
    // 根据返回结果， 进行业务处理
    const { code, data, message } = resp.data;

    if(code === 200) {
      antdMessage.success(message);
      navigate('/')
      // 数据存储
      localStorage.setItem('nickname', data.nickname)
      localStorage.setItem('avator', data.avator)
      localStorage.setItem('tel', data.tel)
      localStorage.setItem('email', data.email)
      localStorage.setItem('role', data.role)
      localStorage.setItem('token', data.token)
    } else {
      antdMessage.error(message)
    }
  };
  return (
    <div className="login">
      <div className="login-content">
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={finish}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: "请输入用户名",
              },
              {
                pattern: /^(1[3-9]\d{9})|(\w+@\w+\.(com|cn|net))$/,
                message: '用户名必须是手机号或者邮箱'
              }
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码",
              },
              {
                pattern: /^\w{6,12}$/,
                message: '密码必须由12位数字,字母,下划线组成'
              }
            ]}
          >
            <Input></Input>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 20, offset: 4 }}>
            <Button block type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
